package pc

import (
	"chess_platform/internal/alisdk"
	. "chess_platform/internal/common"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/orm"
	"io/ioutil"
)

//生成游戏列表配置
func MakeGameConfigFile(multiOrm ...orm.Ormer) error {
	sql := fmt.Sprintf(`
		SELECT
			game_id,name
		FROM
			%v
	`, TableGameList)
	o := NewOrm(multiOrm, DBChessSysData)
	var game []orm.Params
	_, err := o.Raw(sql).Values(&game)
	if err != nil {
		return err
	}
	tmp := make(map[string]interface{}, len(game))
	for _, v := range game {
		tmp[v["game_id"].(string)] = v
	}

	data, err := json.Marshal(tmp)
	if err != nil {
		return err
	}
	filename := "conf/static/game_config.json"
	err = ioutil.WriteFile(filename, data, 0666)
	if err != nil {
		return err
	}
	err = alisdk.PutFileToOSS(filename, PlatformRunMode+"/"+filename)
	if err != nil {
		LogPc.Error(fmt.Sprintf("上传配置文件:%v失败:%v", filename, err))
		return err
	}
	return nil
}

//生成游戏服务器列表配置
func MakeServerConfigFile(multiOrm ...orm.Ormer) error {
	sql := fmt.Sprintf(`
		SELECT
			svrid,name
		FROM
			%v
	`, TableServerInfo)
	o := NewOrm(multiOrm, DBChessSysData)
	var game []orm.Params
	_, err := o.Raw(sql).Values(&game)
	if err != nil {
		return err
	}
	tmp := make(map[string]interface{}, len(game))
	for _, v := range game {
		tmp[v["svrid"].(string)] = v
	}

	data, err := json.Marshal(tmp)
	if err != nil {
		return err
	}
	filename := "conf/static/server_config.json"
	err = ioutil.WriteFile(filename, data, 0666)
	if err != nil {
		return err
	}
	err = alisdk.PutFileToOSS(filename, PlatformRunMode+"/"+filename)
	if err != nil {
		LogPc.Error(fmt.Sprintf("上传配置文件:%v失败:%v", filename, err))
		return err
	}
	return nil
}
